<template>
  <div class="exercise-platform">
    <el-card class="platform-card" v-loading="loading">
      <!-- 头部区域 -->
      <template #header>
        <div class="platform-header">
          <div class="header-left">
            <h2>{{ exerciseSet.title || '练习平台' }}</h2>
            <el-tag type="info" class="count-tag">{{ currentIndex + 1 }}/{{ exercises.length }}</el-tag>
          </div>
          <div class="header-actions">
            <el-button @click="goBack" :icon="Back">返回</el-button>
          </div>
        </div>
      </template>

      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="5" animated />
      </div>

      <div v-else-if="!exerciseSet.id" class="empty-state">
        <el-empty description="未找到练习集" :image-size="200">
          <el-button type="primary" @click="goBack">返回列表</el-button>
        </el-empty>
      </div>

      <div v-else-if="exercises.length === 0" class="empty-state">
        <el-empty description="该练习集没有题目" :image-size="200">
          <el-button type="primary" @click="goBack">返回列表</el-button>
        </el-empty>
      </div>

      <div v-else class="platform-content">
        <el-row :gutter="20">
          <!-- 左侧题目导航 - 在小屏幕上占满宽度，在大屏幕上占较小宽度 -->
          <el-col :xs="24" :sm="24" :md="6" :lg="6" :xl="6">
            <div class="nav-section">
              <div class="nav-header">
                <h3>题目导航</h3>
                <div class="question-count">{{ currentIndex + 1 }}/{{ exercises.length }}</div>
              </div>
              
              <div class="number-grid">
                <el-button
                  v-for="(_, index) in exercises"
                  :key="index"
                  :type="getCurrentButtonType(index)"
                  class="number-button"
                  @click="goToQuestion(index)"
                >
                  {{ index + 1 }}
                </el-button>
              </div>
              
              <div class="action-row">
                <el-button 
                  type="warning" 
                  class="action-button"
                  @click="markQuestion"
                >
                  {{ isCurrentQuestionMarked ? '取消标记' : '标记题目' }}
                </el-button>
                <el-button 
                  type="info" 
                  class="action-button"
                  @click="showAnswer = !showAnswer"
                >
                  {{ showAnswer ? '隐藏答案' : '查看答案' }}
                </el-button>
              </div>
            </div>
          </el-col>
          
          <!-- 右侧题目内容 - 在小屏幕上占满宽度，在大屏幕上占较大宽度 -->
          <el-col :xs="24" :sm="24" :md="18" :lg="18" :xl="18">
            <div class="question-section">
              <div class="question-content">
                <h3>{{ currentQuestion.content }}</h3>
              </div>
              
              <div class="answer-section">
                <el-input
                  v-model="userAnswer"
                  type="textarea"
                  :rows="5"
                  placeholder="请输入你的答案"
                  resize="none"
                />
                
                <div class="button-row">
                  <el-button type="primary" @click="submitAnswer">提交答案</el-button>
                  <el-button @click="nextQuestion" :disabled="currentIndex === exercises.length - 1">下一题</el-button>
                </div>
              </div>
              
              <div class="reference-answer" v-if="showAnswer">
                <h4>参考答案</h4>
                <div class="answer-text">{{ currentQuestion.answer || '暂无参考答案' }}</div>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Back } from '@element-plus/icons-vue'
import http from '../utils/axios'

const router = useRouter()
const route = useRoute()

// 状态变量
const loading = ref(true)
const exerciseSet = ref({})
const exercises = ref([])
const currentIndex = ref(0)
const userAnswer = ref('')
const showAnswer = ref(false)
const markedQuestions = ref(new Set())
const records = ref([])

// 计算属性
const currentQuestion = computed(() => {
  if (!exercises.value || exercises.value.length === 0) {
    return {}
  }
  
  if (currentIndex.value < 0 || currentIndex.value >= exercises.value.length) {
    currentIndex.value = 0
  }
  
  return exercises.value[currentIndex.value] || {}
})

const isCurrentQuestionMarked = computed(() => {
  return currentQuestion.value && markedQuestions.value.has(currentQuestion.value.id)
})

// 获取练习集详情
const fetchExerciseSet = async () => {
  loading.value = true
  try {
    const id = route.params.id
    if (!id || id === 'undefined') {
      ElMessage.error('练习集ID无效，无法获取练习集详情')
      loading.value = false
      return
    }
    
    const response = await http.get(`/exercises/exercise-sets/${id}/`)
    exerciseSet.value = response.data
    
    // 统一使用exercises数组
    if (response.data.exercises && Array.isArray(response.data.exercises)) {
      exercises.value = response.data.exercises
    } else if (response.data.questions && Array.isArray(response.data.questions)) {
      exercises.value = response.data.questions
    } else {
      exercises.value = []
    }
    
    await fetchRecords()
    
    // 如果有题目，设置当前题目为第一题
    if (exercises.value.length > 0) {
      currentIndex.value = 0
    }
  } catch (error) {
    console.error('获取练习集详情失败:', error)
    ElMessage.error('获取练习集详情失败')
    
    // 如果是404错误，可能是ID无效，重定向到练习集列表
    if (error.response && error.response.status === 404) {
      router.replace('/dashboard/exercises')
    }
  } finally {
    loading.value = false
  }
}

// 获取练习记录
const fetchRecords = async () => {
  try {
    const response = await http.get(`/exercises/records/`, {
      params: {
        exercise_set: route.params.id
      }
    })
    records.value = Array.isArray(response.data) ? response.data : []
  } catch (error) {
    console.error('获取练习记录失败:', error)
    records.value = []
  }
}

// 提交答案
const submitAnswer = async () => {
  if (!currentQuestion.value || !currentQuestion.value.id) {
    ElMessage.warning('无效的题目')
    return
  }
  
  try {
    const response = await http.post('/exercises/records/', {
      exercise: currentQuestion.value.id,
      user_answer: userAnswer.value
    })
    
    ElMessage.success('答案已提交')
    
    // 刷新记录
    await fetchRecords()
    
    // 自动进入下一题
    if (currentIndex.value < exercises.value.length - 1) {
      nextQuestion()
    }
  } catch (error) {
    console.error('提交答案失败:', error)
    ElMessage.error('提交答案失败')
  }
}

// 导航方法
const goBack = () => {
  router.push('/dashboard/exercises')
}

const nextQuestion = () => {
  if (currentIndex.value < exercises.value.length - 1) {
    currentIndex.value++
    userAnswer.value = ''
    showAnswer.value = false
  }
}

const goToQuestion = (index) => {
  currentIndex.value = index
  userAnswer.value = ''
  showAnswer.value = false
}

// 标记题目
const markQuestion = () => {
  if (!currentQuestion.value) return
  const questionId = currentQuestion.value.id
  if (markedQuestions.value.has(questionId)) {
    markedQuestions.value.delete(questionId)
  } else {
    markedQuestions.value.add(questionId)
  }
}

// 获取按钮类型
const getCurrentButtonType = (index) => {
  if (index === currentIndex.value) {
    return 'primary'
  }
  
  // 检查是否已回答
  if (currentQuestion.value && records.value.some(r => r.exercise === exercises.value[index]?.id)) {
    return 'success'
  }
  
  // 检查是否已标记
  if (exercises.value[index] && markedQuestions.value.has(exercises.value[index].id)) {
    return 'warning'
  }
  
  return 'default'
}

// 在组件挂载时获取数据
onMounted(() => {
  fetchExerciseSet().then(() => {
    // 检查URL中是否有start参数，如果有则跳转到指定题目
    if (route.query.start && !isNaN(parseInt(route.query.start))) {
      const startIndex = parseInt(route.query.start)
      if (startIndex >= 0 && exercises.value.length > startIndex) {
        currentIndex.value = startIndex
      }
    }
  })
})
</script>

<style scoped>
.exercise-platform {
  padding: 20px;
  min-height: 100vh;
  color: var(--el-text-color-primary);
}

.platform-card {
  background: rgba(255, 255, 255, 0.05);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.1);
}

.platform-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.header-left h2 {
  margin: 0;
}

.count-tag {
  margin-left: 8px;
}

.loading-container, .empty-state {
  padding: 40px;
  text-align: center;
}

.platform-content {
  margin-top: 20px;
}

/* 确保行正确显示 */
.el-row {
  display: flex;
  flex-wrap: wrap;
  margin-right: -10px;
  margin-left: -10px;
}

/* 确保列正确显示 */
.el-col {
  box-sizing: border-box;
  padding-right: 10px;
  padding-left: 10px;
}

.nav-section {
  background: rgba(255, 255, 255, 0.03);
  border-radius: 8px;
  padding: 16px;
  border: 1px solid rgba(255, 255, 255, 0.05);
  margin-bottom: 20px;
  display: block;
  width: 100%;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.nav-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.nav-header h3 {
  margin: 0;
}

.number-grid {
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  gap: 8px;
  margin-bottom: 16px;
}

.number-button {
  padding: 8px;
  height: auto;
}

.action-row {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.action-button {
  width: 100%;
}

.question-section {
  background: rgba(255, 255, 255, 0.03);
  border-radius: 8px;
  padding: 20px;
  border: 1px solid rgba(255, 255, 255, 0.05);
}

.question-content {
  margin-bottom: 20px;
}

.question-content h3 {
  margin-top: 0;
  white-space: pre-wrap;
}

.answer-section {
  margin-bottom: 20px;
}

.button-row {
  display: flex;
  justify-content: flex-start;
  gap: 10px;
  margin-top: 16px;
}

.reference-answer {
  margin-top: 20px;
  padding: 16px;
  background: rgba(255, 255, 255, 0.02);
  border-radius: 8px;
  border: 1px solid rgba(255, 255, 255, 0.05);
}

.reference-answer h4 {
  margin-top: 0;
  margin-bottom: 10px;
  color: var(--el-color-primary);
}

.answer-text {
  white-space: pre-wrap;
}

@media (max-width: 768px) {
  .platform-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .header-actions {
    width: 100%;
    display: flex;
    justify-content: space-between;
  }
  
  .platform-content {
    margin-top: 10px;
  }
  
  .nav-section, .question-section {
    margin-bottom: 20px;
  }
  
  /* 调整题目网格在移动设备上的显示 */
  .number-grid {
    grid-template-columns: repeat(4, 1fr);
  }
  
  /* 确保在移动设备上有足够的间距 */
  .el-col {
    margin-bottom: 15px;
  }
}

/* 确保在小屏幕上正确显示 */
@media (max-width: 992px) {
  .el-col[class*=el-col-md] {
    margin-bottom: 20px;
  }
}
</style> 